/*
 * File: Pyramid.java
 * Name: Diego A. Falciola
 * Section Leader: Sam King 
 * ------------------
 * This file is the starter file for the Pyramid problem.
 * It includes definitions of the constants that match the
 * sample run in the assignment, but you should make sure
 * that changing these values causes the generated display
 * to change accordingly.
 */

import acm.graphics.*;
import acm.program.*;

public class Pyramid extends GraphicsProgram {

	/** Width of each brick in pixels */
	private static final int BRICK_WIDTH = 30;

	/** Height of each brick in pixels */
	private static final int BRICK_HEIGHT = 12;

	/** Number of bricks in the base of the pyramid */
	private static final int BRICKS_IN_BASE = 14;
	
	/** Middle point of the screen */
	double midPoint = 0;
	
	public void run() {
		drawPyramid();
	}
	
	/**
	 *  Draw a pyramid of BRICKS_IN_BASE-1 rows 
	 *  of BRICK_WIDTH*BRICK_HEIGHT size 
	 */
	private void drawPyramid(){
		// calculate midPoint, only once and reuse it later
		midPoint = getWidth()/2;
		
		for (int brickRowsLeft=BRICKS_IN_BASE; brickRowsLeft>=0; brickRowsLeft--){
			GPoint startPoint = getStartPoint(brickRowsLeft);

			drawLine(startPoint, brickRowsLeft);
		}
	}
	
	/**
	 * Draw a line of bricksLeft bricks, starting from startPoint
	 * @param startPoint initial point of the line
	 * @param bricksLeft number of bricks to build in the row
	 */
	private void drawLine(GPoint startPoint, int bricksLeft){
		for(int i=0; i<bricksLeft+1; i++){
			drawBrick(startPoint.getX() + i*BRICK_WIDTH, startPoint.getY());
		}
	}
	
	/**
	 * Draw a brick at x,y
	 * @param x 
	 * @param y
	 */
	private void drawBrick(double x, double y){
		GRect rect = new GRect(x, y,BRICK_WIDTH,BRICK_HEIGHT);
		add(rect);
	}
	
	/**
	 * Initial point to build a row
	 * @param bricksLeft number of bricks to build in the row
	 * @return initial point to build a row
	 */
	private GPoint getStartPoint(int bricksLeft){		
		double x = getStartX(midPoint, bricksLeft);
		double y = getStartY(bricksLeft); 
		
		return new GPoint(x,y);
	}
	
	/**
	 * Start position in the X axe.
	 * Formula: midPoint - (bricksLeft*BRICK_WIDTH)/2
	 * 
	 * @param midPoint middle point of the screen
	 * @param bricksLeft number of bricks to build in the row 
	 * @return
	 */
	private double getStartX(double midPoint, int bricksLeft){
		return midPoint - (bricksLeft*BRICK_WIDTH)/2;
	}
	
	/**
	 * Start position in the Y axe
	 * Formula: return getHeight() - (BRICKS_IN_BASE-bricksLeft)*BRICK_HEIGHT;
	 * 
	 * @param bricksLeft
	 * @return
	 */
	private double getStartY(int bricksLeft){
		return getHeight() - (BRICKS_IN_BASE-bricksLeft)*BRICK_HEIGHT;
	}
}

